import moment from 'moment';

/**
 * 工具类
 */
export class Utils {
  static handleUrl(pre_url, ...args) {
    let url = pre_url;
    for (let i = 0; i < args.length; i++) {
      const index = `{${i}}`;
      url = url.replace(index, args[i]);
    }
    return url;
  };

  static formatTime(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
    return moment(date).format(fmt);
  }

  /**
   * 针对应用信息取唯一hash标识
   *
   * @param{string} appId
   * @param{string} appSecret
   * @param{string} key 存储cookie的键
   * @return {*}
   */
  static genAppInfo(appId, appSecret, key = '_hash') {
    const text = `{\"app_id\":\"${appId}\",\"app_secret\":\"${appSecret}\"}`;
    const hash = Buffer.from(text, 'utf8').toString('base64');
    localStorage.setItem(key, hash);
    return hash;
  };

  /**
   *
   * @param{Function} callback
   * @param{number} delay
   * @param{boolean} immediate
   * @return {(function(...[*]=): void)|*}
   */
  static getDebounceCallbackFn(callback, delay, immediate = false) {
    let timer;
    return (...args) => {
      if (immediate) {
        callback.apply(this, args);
        immediate = false;
        return;
      }
      clearTimeout(timer);
      timer = setTimeout(() => {
        callback.apply(this, args);
      }, delay);
    };
  }

  /**
   *
   * 节流函数
   * @param{Function} callback
   * @param{number} delay
   * @return {(function(...[*]=): void)|*}
   */
  static getThrottleCallbackFn(callback, delay = 16) {
    return (...args) => {
      let timer;
      return new Promise((resolve, reject) => {
        if (timer) {
          reject(new Error('请求间隔必须大于16ms'));
          return;
        }
        timer = setTimeout(() => {
          resolve(callback.apply(this, args));
          clearTimeout(timer);
        }, delay);
      });
    };
  };
}

